from django.shortcuts import render
from fruit.models import User, Goods


# Create your views here.

# 登录
def index_view(request):
    pass


def login_view(request):
    if request.method == "POST":
        user_name = request.POST.get('user_name', '')
        pass_word = request.POST.get('pwd', '')
        user = User.objects.filter(user_name=user_name)
        if user:
            if pass_word == user[0].pwd:
                request.session['IS_LOGIN'] = True
                request.session['user_name'] = user_name
                request.session['user_id'] = user[0].id
                return index_view(request)
            else:
                return render(request, 'login.html', {'error': '用户密码错误'})
        else:
            return render(request, 'login.html', {'error': '用户不存在'})
    else:
        return render(request, 'login.html')


def register_view(request):
    if request.method == "POST":
        user_name = request.POST.get('user_name')
        pwd = request.POST.get("pwd")
        cpwd = request.POST.get("cpwd")
        phone = request.POST.get("phone")
        print("============oo" + user_name)
        user = User.objects.filter(user_name=user_name)
        print(user)
        if user:
            return render(request, 'register.html', {"error": f"{user_name}已存在"})
        if pwd != cpwd:
            return render(request, 'register.html', {"error": "密码不一致"})
        if len(user_name) > 0 and len(pwd) > 0 and len(phone) > 0:
            user = User()
            user.user_name = user_name
            user.pwd = pwd
            user.phone = phone
            user.save()
            return render(request, "login.html")
        else:
            return render(request, "register.html", {"error": "用户名、密码、手机号不能为空"})
    else:
        return render(request, "register.html")


# 退出登录
def login_out(request):
    request.session.flush()
    return render(request, 'login.html')


def index_view(request):
    goods_list = Goods.objects.all()
    return render(request, 'index.html', {"good_list": goods_list, 'user_name': request.session.get('user_name', None)})


def goodDetail(request, id, ):
    good_detail = Goods.objects.get(id=id)
    return render(request, 'detail.html', {"good": good_detail, 'user_name': request.session.get('user_name', None)})
